import tkinter as tk
from tkinter import filedialog, messagebox
import os
import edit
from urllib.parse import urlparse  # 用于URL验证

from 自动填写前端价格 import onepiece

# 创建主窗口
root = tk.Tk()
root.title("查询shin价格")


# 定义选择文件夹的函数
def select_folder():
    folder_path = filedialog.askdirectory()
    if folder_path:
        entry_folder_path.delete(0, tk.END)
        entry_folder_path.insert(0, folder_path)


# 定义调用 edit_price 方法的函数
def call_edit_price():
    folder_path = entry_folder_path.get()
    if not folder_path:
        messagebox.showwarning("警告", "请先选择文件夹！")
    elif not os.path.isdir(folder_path):
        messagebox.showerror("错误", "输入的路径不是一个有效的文件夹！")
    else:
        edit.edit_price(folder_path)


# 新增：处理URL输入的函数
def handle_url_input():
    url = entry_url.get().strip()

    # 基本URL验证
    try:
        result = urlparse(url)
        if not all([result.scheme, result.netloc]):
            raise ValueError
    except:
        messagebox.showerror("错误", "请输入有效的URL格式（需包含http/https协议）")
        return

    # 调用a.py的b方法（假设edit模块有b方法）
    try:
        onepiece.getimg(url)  # 调用目标方法
        messagebox.showinfo("成功", "URL已成功提交处理")
    except Exception as e:
        messagebox.showerror("错误", f"处理URL时发生错误：\n{str(e)}")


# GUI布局调整
# 原有文件夹选择部分
label_folder_path = tk.Label(root, text="文件夹路径：")
label_folder_path.grid(row=0, column=0, padx=10, pady=5)

entry_folder_path = tk.Entry(root, width=50)
entry_folder_path.grid(row=0, column=1, padx=10, pady=5)

button_select_folder = tk.Button(root, text="选择文件夹", command=select_folder)
button_select_folder.grid(row=0, column=2, padx=10, pady=5)

# 新增URL输入部分
label_url = tk.Label(root, text="请输入URL：")
label_url.grid(row=1, column=0, padx=10, pady=5)

entry_url = tk.Entry(root, width=50)
entry_url.grid(row=1, column=1, padx=10, pady=5)

button_submit_url = tk.Button(root,
                              text="提交URL",
                              command=handle_url_input,
                              bg="#e0e0ff")  # 不同颜色区分功能
button_submit_url.grid(row=1, column=2, padx=10, pady=5)

# 原有查询按钮
button_call_edit_price = tk.Button(root,
                                   text="查询价格",
                                   command=call_edit_price,
                                   bg="#ffe0e0")
button_call_edit_price.grid(row=2, column=1, padx=10, pady=10)

# 启动主循环
root.mainloop()